<template>
    <div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="120px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="结算单位">
                        <search-custom @selectName="v=>condition['search_LIKE_accountUnit']=v" :isShipAgent="true"></search-custom>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算月度起">
                        <!--<el-date-picker v-model="condition['search_GTE_accountMonth']"-->
                        <!--:picker-options="startPickerOptions" type="date" placeholder="起始日期"-->
                        <!--format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>-->
                        <el-date-picker v-model="condition['search_GTE_accountMonth']"
                                        :picker-options="startPickerOptions" value-format="yyyy-MM" type="month"
                                        placeholder="起始日期"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算月度止">
                        <!--<el-date-picker v-model="condition['search_LTE_accountMonth']" @change="handleChangeEnd"
                                        :picker-options="endPickerOptions" type="date" placeholder="结束日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>-->
                        <el-date-picker v-model="condition['search_LTE_accountMonth']"
                                        :picker-options="endPickerOptions" value-format="yyyy-MM" type="month"
                                        placeholder="结束日期"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-button type="primary" class="ml-120" @click="loadData">查 询</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                    <el-button @click="dialogForm = true" v-if="power('TALLY_BILL_MONTHLIST:CALCALL')">月结账单计算
                    </el-button>
                    <el-button @click="handleMonthPrint('monthTotal')">月结账单打印</el-button>
                    <el-button @click="toExcel">月结账单导出</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-row type="flex" justify="end" class="mt-10 ">
            <el-col :span="16" style="display: flex;justify-content: space-between">
                <title-point color="#50B155">
                    <div slot="content">
                        总艘次 :
                        <span style="font-size: 16px">{{ totalLoad }}</span>
                    </div>
                </title-point>
                <title-point color="#449DFF">
                    <div slot="content">
                        总理箱TEU :
                        <span style="font-size: 16px">{{ totalLoadTEU }}</span></div>
                </title-point>
                <title-point color="#30C8CA">
                    <div slot="content">
                        应结金额 :
                        <span style="font-size: 16px">{{ fee }}</span></div>
                </title-point>
            </el-col>
        </el-row>
        <div style="display: flex">
            <div id="pieOne" class="balance-classCount-style"></div>
            <div id="pieTwo" class="balance-classCount-style"></div>
        </div>
        <el-row type="flex" justify="end" class="mt-10 ">
            <el-col :span="16" style="display: flex;justify-content: space-between">
                <title-point color="#50B155">
                    <div slot="content">
                        卸船艘次 :
                        <span style="font-size: 16px">{{ unload }}</span>
                    </div>
                </title-point>
                <title-point color="#449DFF">
                    <div slot="content">
                        卸船理箱TEU :
                        <span style="font-size: 16px">{{ unloadTEU }}</span></div>
                </title-point>
                <title-point color="#30C8CA">
                    <div slot="content">
                        装船艘次 :
                        <span style="font-size: 16px">{{ load }}</span></div>
                </title-point>
                <title-point color="#6DC789">
                    <div slot="content">
                        装船理箱TEU :
                        <span style="font-size: 16px">{{ loadTEU }} </span>
                    </div>
                </title-point>
                <title-point color="#B798F5">
                    <div slot="content">
                        特殊理箱TEU :
                        <span style="font-size: 16px">{{ spTEU }} </span>
                    </div>
                </title-point>
            </el-col>
        </el-row>
        <el-table :data="list" v-loading="listLoading" border stripe max-height="500" class="mt-10">
            <el-table-column type="index" fixed="left" label="序号" width="55">
                <template slot-scope="scope">
                    {{ scope.$index+1 }}
                </template>
            </el-table-column>
            <el-table-column prop="accountUnit" label="结算单位"  min-width="120"></el-table-column>
            <el-table-column prop="accountMonth" label="结算月度"  min-width="120"></el-table-column>
            <el-table-column prop="unloadVoyNum" label="卸船艘次"  min-width="120"></el-table-column>
            <el-table-column prop="unloadTeu" label="卸船理箱TEU"  min-width="140"></el-table-column>
            <el-table-column prop="uploadVoyNum" label="装船艘次"  min-width="120"></el-table-column>
            <el-table-column prop="uploadTeu" label="装船理箱TEU"  min-width="140"></el-table-column>
            <el-table-column prop="zxTeu" label="装箱TEU"  min-width="140"></el-table-column>
            <el-table-column prop="cxTeu" label="拆箱TEU"  min-width="140"></el-table-column>
            <el-table-column prop="specialTeu" label="特殊理箱TEU"  min-width="140"></el-table-column>
            <el-table-column prop="totalTeu" label="总理箱TEU"  min-width="140"></el-table-column>
            <el-table-column prop="accountFee" label="应结金额"  min-width="140"></el-table-column>
            <el-table-column prop="createBy" label="创建人"  min-width="120"></el-table-column>
            <el-table-column prop="createDateTime" label="创建时间"  min-width="160"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作"  width="140">
                <template slot-scope="scope">
                    <el-button size="small" v-if="power('TALLY_BILL_MONTHLIST:DETAIL')" type="text"
                               @click="handleSee(scope.row)">查看
                    </el-button>
                    <el-button size="small" v-if="power('TALLY_BILL_MONTHLIST:CALCDETAIL')" type="text"
                               @click="handleRecalculation(scope.row)">重算
                    </el-button>
                    <el-button size="small" type="text"
                               @click="handleAdjustAccount(scope.row)">调账
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="mt-10" type="flex" justify="space-between" v-show="total>0">
            <div class="oper">

            </div>
            <el-pagination class="page" @size-change="size=>pageInfo.iDisplayLength=size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :current-page.sync="pageInfo.pageStart" :page-sizes="pageInfo.pageArr"
                           :page-size="pageInfo.iDisplayLength" :total="total">
            </el-pagination>
        </el-row>
        <el-dialog title="月结账单结算" :visible.sync="dialogForm" width="400px">
            <el-form :inline="true" :model="form" ref="form" class="search-form mt-20" :rules="rules"
                     label-width="120px">
                <el-row type="flex" justify="center">
                    <el-col :span="24">
                        <el-form-item label="结算月度：" prop="accountMonth">
                            <el-date-picker v-model="form.accountMonth" @change="handleSelectDate" type="month"
                                            value-format="yyyy-MM"
                                            placeholder="选择月">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="24">
                        <el-form-item label="发生日期：" prop="">
                            <div v-show="form.startFeeTime">{{ form.startFeeTime }}</div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="24">
                        <el-form-item label="全部/单位计算：" prop="allUnit">
                            <el-radio v-model="form.allUnit" :label="true">全部计算</el-radio>
                            <el-radio v-model="form.allUnit" :label="false">指定单位计算</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="24" v-if="!form.allUnit">
                        <el-form-item label="指定单位结算：" prop="">
                            <search-custom @selectName="v=>form.accountUnit=v" :isShipAgent="true"></search-custom>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogForm = false">取 消</el-button>
                <el-button type="primary" @click="handleComputed(form)" :loading="$store.getters.loadingBtn">计 算
                </el-button>
            </div>
        </el-dialog>
        <adjust-account-form ref="adjustAccountForm" @load="loadData"></adjust-account-form>
        <!-- 新加导出月结账单 -->
        <table class="monthCh" v-show="showMonthTip" border="1" cellspacing="0" style="width: 800px;border-top: none;">
            <tr>
                <td colspan="6" style="text-align:center">
                    <h3 style="text-align:center">{{showMonth}}账单汇总表</h3>
                </td>
            </tr>
            <tr style="text-align: center;">
                <td rowspan="2" width="15%">结算单位</td>
                <td rowspan="2" width="25%">业务项目</td>
                <td rowspan="2" width="15%">箱量</td>
                <td colspan="3">账单</td>
            </tr>
            <tr style="text-align: center;">
                <td width="15%">计费箱量</td>
                <td width="15%">费率</td>
                <td width="15%">金额</td>
            </tr>
            <tbody v-for="(items, indexs) of lists">
                <tr v-for="(item, index) of items.totaldata" :style="item.portIMEX == '本月小计(箱量/收入)' ? 'background-color:#cdcdcd':''">
                    <td style="height: 25px;width: 15%;text-align: center;" v-if="index == 0" :rowspan="items.totaldata.length">{{items.accountUnit}}</td>
                    <td style="width: 25%;" >{{item.portIMEX}}</td>
                    <td style="width: 15%;">{{item.showContainerNum}}</td>
                    <td style="width: 15%;">{{(Number(item.containerNum4) + Number(item.containerNum2))== 0 ? "" : (Number(item.containerNum4) + Number(item.containerNum2))}}</td>
                    <td style="width: 15%;">{{item.strFeeRate}}</td>
                    <td style="width: 15%;">{{item.money}}</td>
                </tr>
            </tbody>
        </table>
        
    </div>
</template>

<script>
    import { getBalance, monthBalance, getAccountRange, getOperationTotalReportByMonth } from "@/api/balance/balance";
    import { getSystemParameterList } from "@/api/system/systemParameter";
    import searchCustom from '@/components/autocomplete/autoSearchCustom';
    import adjustAccountForm from "./adjustAccountForm";
    import { newExportExcel } from "@/utils/newExport";
    import titlePoint from '../common/title-point'
    // 引入基本模板
    let echarts = require("echarts/lib/echarts");
    import "echarts/theme/macarons";
    import {getLocalTime} from "../../../utils/dateFormat";
    // 引入提示框和title组件
    require("echarts/lib/component/tooltip");
    require("echarts/lib/component/title");
    require("echarts/lib/chart/pie");
    export default {
        name: "结算对账单",
        components: {
            searchCustom, titlePoint, adjustAccountForm
        },
        data() {
            return {
                condition: {
                    search_GTE_accountMonth: '',
                    search_LTE_accountMonth: '',
                    search_LIKE_accountUnit: '',
                },
                list: [],
                showMonth: '',
                lists: [],  //新加导出月结账单
                showMonthTip: false,
                total: 0,
                pageInfo: this.$defalutPage(),
                listLoading: false,
                dialogForm: false,
                form: this.clearForm(),
                rules: {},
                paramValue: '',
                unload: 0,
                unloadTEU: 0,
                load: 0,
                loadTEU: 0,
                spTEU: 0,
                totalLoad: 0,
                totalLoadTEU: 0,
                fee: 0,
                pieOne: '',
                pieTwo: '',
                created: true,
                billIds : ''
            }
        },
        mounted() {
            let day = sessionStorage.getItem('balanceIndexFirst')
            let lastDay = sessionStorage.getItem('balanceIndexLast')
            this.condition['search_GTE_accountMonth'] = day + ' 00:00:00'
            this.condition['search_LTE_accountMonth'] = lastDay + ' 23:59:59'
            this.loadData()
        },
        activated() {
            if (this.created) {
                this.loadData()
            }
        },
        methods: {
            loadData() {
                this.listLoading = true
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = this.pageInfo.iDisplayLength
                params.sortType = '-createDateTime'
                getBalance(params).then(res => {
                    this.created = false
                    const data = res.data
                    this.total = data.iTotalRecords
                    this.listLoading = false
                    this.list = data.aaData
                    let unload = 0, unloadTEU = 0, load = 0, loadTEU = 0, spTEU = 0, fee = 0
                    if (this.list.length > 0) {
                        let ids = ""
                        this.list.forEach(f => {
                            ids = ids + "," + f.id
                            unload = unload + f.unloadVoyNum
                            unloadTEU = unloadTEU + f.unloadTeu
                            load = load + f.uploadVoyNum
                            loadTEU = loadTEU + f.uploadTeu
                            spTEU = spTEU + f.specialTeu
                            fee = fee + Number(f.accountFee)
                        })
                        this.billIds = ids == "" ? "" : ids.substring(1)
                        this.totalLoad = unload + load
                        this.totalLoadTEU = unloadTEU + loadTEU + spTEU
                        this.fee = fee
                        this.unload = unload
                        this.unloadTEU = unloadTEU
                        this.load = load
                        this.loadTEU = loadTEU
                        this.spTEU = spTEU
                    }
                    this.pieOne = echarts.init(
                        document.getElementById("pieOne"),
                        "macarons"
                    );
                    this.pieOne.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c} ({d}%)"
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: ['装船', '卸船']
                        },
                        series: [
                            {
                                // name: '访问来源',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: [{ value: this.load, name: '装船' }, { value: this.unload, name: '卸船' }],
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    })
                    this.pieTwo = echarts.init(
                        document.getElementById("pieTwo"),
                        "macarons"
                    );
                    this.pieTwo.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c} ({d}%)"
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: ['装船', '卸船', '特殊箱']
                        },
                        series: [
                            {
                                // name: '访问来源',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: [{ value: this.loadTEU, name: '装船' }, {
                                    value: this.unloadTEU,
                                    name: '卸船'
                                }, { value: this.spTEU, name: '特殊箱' }],
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    })
                })

                getSystemParameterList({ 'search_LIKE_paramCode': 'financial_account_day' }).then(res => {
                    if (res.data.aaData.length > 0) {
                        this.paramValue = res.data.aaData[0].paramValue
                    }
                })
            },
            handleMonthPrint(router){
                let params = this.$assist.copySearchConditions(this.condition)
                getOperationTotalReportByMonth (params).then(res => {
                    localStorage.setItem('monthTotalData', JSON.stringify(res.data.aaData))
                    const origin = window.location.origin + window.location.pathname
                    const route = `#/${router}/`
                    let showMonth = ""
                    if (this.condition.search_GTE_accountMonth != "" || this.condition.search_LTE_accountMonth != "") {
                        let showGteMonth = this.condition.search_GTE_accountMonth == "" ? "" : (new Date(this.condition.search_GTE_accountMonth).getFullYear()+"年"+(new Date(this.condition.search_GTE_accountMonth).getMonth()+1)+"月")
                        let showLteMonth = this.condition.search_LTE_accountMonth == "" ? "" : (new Date(this.condition.search_LTE_accountMonth).getFullYear()+"年"+(new Date(this.condition.search_LTE_accountMonth).getMonth()+1)+"月")
                        if (showGteMonth == showLteMonth) {
                            showMonth = showGteMonth
                        } else {
                            showMonth = showGteMonth + "-" + showLteMonth
                        }
                    }
                    localStorage.setItem('monthTotalDataShowMonth', showMonth)
                    window.open(`${origin}${route}`);
                })

            },
            handleExport() {
                let map = new Map();
                map.set('accountUnit', '结算单位')
                map.set('accountMonth', '结算月度')
                map.set('unloadVoyNum', '卸船艘次')
                map.set('unloadTeu', '卸船理箱TEU')
                map.set('uploadVoyNum', '装船艘次')
                map.set('uploadTeu', '装船理箱TEU')
                map.set('specialTeu', '特殊理箱TEU')
                map.set('zxTeu', '装箱TEU')
                map.set('cxTeu', '拆箱TEU')
                map.set('totalTeu', '总理箱TEU')
                map.set('accountFee', '应结金额')
                map.set('createBy', '创建人')
                map.set('createDateTime', '创建时间')
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = 9999
                getBalance(params).then(res => {
                    let exportRecords = [];
                    let exportArr = res.data.aaData;
                    exportArr.forEach(record => {
                        let exportRecord = {};
                        for (let [key, value] of map.entries()) {
                            exportRecord[value] = record[key];
                        }
                        exportRecords.push(exportRecord);
                    });
                    newExportExcel("结算对账单", exportRecords);
                })
            },
            handleComputed(item) {
                let data = {
                    accountMonth: item.accountMonth,
                    allUnit: item.allUnit,
                    accountUnit: item.accountUnit,
                }
                monthBalance(data).then(res => {
                    this.$message({ message: '计算成功!', type: 'success' })
                    this.dialogForm = false
                    this.loadData()
                })
            },
            handleSee(item) {
                sessionStorage.setItem('balanceDetailId', item.id)
                this.$router.push({ path: '/work/balanceDetail', name: '对账单查看' })
            },
            handleRecalculation(item) {
                this.$confirm('是否确认重算？', '提示', {}).then(() => {
                    let data = {
                        accountMonth: item.accountMonth.substr(0, 7),
                        allUnit: false,
                        accountUnit: item.accountUnit,
                    }
                    this.handleComputed(data)
                })

            },
            handleAdjustAccount(item) {
                this.$refs.adjustAccountForm.userName = this.$store.getters.currentUser.org.name
                this.$refs.adjustAccountForm.form.accountUnit = item.accountUnit
                this.$refs.adjustAccountForm.form.accountMonth = item.accountMonth
                this.$refs.adjustAccountForm.form.accountBillId = item.id
                this.$refs.adjustAccountForm.dialogAdjustForm = true;
            },
            handleSelectDate(val) {
                getAccountRange(val).then(res => {
                    this.form.startFeeTime = res.data
                })
            },
            handleChangeEnd(val) {
                let setVal = val;
                if (val) {
                    setVal = val.split(" ")[0] + " 23:59:59";
                }
                this.condition["search_LTE_accountMonth"] = setVal;
            },
            clearForm() {
                return {
                    allUnit: true,
                    startFeeTime: '',
                    endFeeTime: '',
                    accountMonth: '',
                    accountUnit: '',
                }
            },
            toExcel() {
                let params = this.$assist.copySearchConditions(this.condition)
                getOperationTotalReportByMonth (params).then(res => {
                    this.lists = res.data.aaData
                    let showMonth = ""
                    if (this.condition.search_GTE_accountMonth != "" || this.condition.search_LTE_accountMonth != "") {
                        let showGteMonth = this.condition.search_GTE_accountMonth == "" ? "" : (new Date(this.condition.search_GTE_accountMonth).getFullYear()+"年"+(new Date(this.condition.search_GTE_accountMonth).getMonth()+1)+"月")
                        let showLteMonth = this.condition.search_LTE_accountMonth == "" ? "" : (new Date(this.condition.search_LTE_accountMonth).getFullYear()+"年"+(new Date(this.condition.search_LTE_accountMonth).getMonth()+1)+"月")
                        if (showGteMonth == showLteMonth) {
                            showMonth = showGteMonth
                        } else {
                            showMonth = showGteMonth + "-" + showLteMonth
                        }
                    }
                    this.showMonth = showMonth
                    this.$nextTick(() => {
                        this.lists
                        this.showMonth
                        this.$forceUpdate()
                    })
                    setTimeout(() => {
                        let title = this.showMonth + '账单汇总表'
                        var table2excel = new Table2Excel(document.getElementsByClassName('monthCh'),{
                            plugins:[
                                Table2Excel.plugins.alignmentPlugin,
                                Table2Excel.plugins.hyperlinkPlugin,
                                {
                                    workcellCreated({
                                        workbook,
                                        tables,
                                        worksheet,
                                        table,
                                        workcell,
                                        cell,
                                        cellStyle,
                                        rowRange,
                                        colRange
                                    }) {
                                        // 单元格边框
                                        workcell.border = {
                                            top: {
                                                style: 'thin'
                                            },
                                            left: {
                                                style: 'thin'
                                            },
                                            bottom: {
                                                style: 'thin'
                                            },
                                            right: {
                                                style: 'thin'
                                            }
                                        };
                                    }
                                }
                            ]
                        })
                        table2excel.export(title, 'xlsx');
                    },1000)
                    
                })
            },
        },
        computed: {
            startPickerOptions() {
                let endDate = this.condition["search_LTE_accountMonth"];
                return {
                    disabledDate(time) {
                        if (endDate) {
                            return time.getTime() > new Date(endDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            endPickerOptions() {
                let startDate = this.condition["search_GTE_accountMonth"];
                return {
                    disabledDate(time) {
                        if (startDate) {
                            return time.getTime() < new Date(startDate).getTime() - 60 * 60 * 24 * 1000;
                        } else {
                            return false;
                        }
                    }
                };
            },
        },
        watch: {
            pageInfo: {
                deep: true,
                handler: function () {
                    this.loadData()
                }
            },
            dialogForm(bool) {
                if (!bool) {
                    this.form = this.clearForm()
                }
            }
        },
    }
</script>

<style scoped>
    #pieOne {
        height: 300px;
    }

    .balance-classCount-style {
        height: 300px;
        width: 100%;
    }
</style>
